﻿using System;
using LeakView.common;
using log4net;

namespace LeakView.service
{

    public class AjaxAnyResult
    {
        public bool success { get; set; }
        public string message { get; set; }
        public object data { get; set; }
    }

    public class AjaxLeakNode
    {
        public string id { get; set; }
        public string name { get; set; }
        public string url { get; set; }
        public double lat { get; set; }
        public double lng { get; set; }
    }

    public class AjaxLeakPair
    {
        public string id { get; set; }
        public string name { get; set; }
        public double length { get; set; }
        public string gps { get; set; }
        public AjaxLeakNode head { get; set; }
        public AjaxLeakNode tail { get; set; }
    }

    public class AjaxLeakPairStatus
    {
        public bool head { get; set; }
        public bool tail { get; set; }
    }

    public class AjaxLeakInfo
    {
        public long id { get; set; }
        public string pairId { get; set; }
        public long time { get; set; }
        public double location { get; set; }
        public long diff { get; set; }
        public double cor { get; set; }
        public string status { get; set; }
        public string statusStr { get; set; }
        public long ackTime { get; set; }
        public string ackUser { get; set; }
    }

    public class AjaxValue<T>
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(AjaxValue<T>));

        private readonly Expirable<T> value = new Expirable<T>(TimeSpan.FromSeconds(20));
        public Expirable<T> Value { get => this.value; }
        

        private readonly AjaxContent content = AjaxContent.Get();
        public AjaxContent Content { get => content; }

        public void fetch(Ajax ajax)
        {
            try
            {
                OnFetchPrepare();

                T v = ajax.DoPost<T>(Content);
                if(v != null)
                {
                    value.update(v);

                    OnFetchFinish();

                    //log.Debug("Value Ajax fetch and updated.");
                }
            }
            catch (Exception e)
            {
                log.Warn("Value Ajax fetch failed.", e);
            }
        }

        public void fetch()
        {
            using(Ajax ajax = new Ajax())
            {
                fetch(ajax);
            }
        }

        protected virtual void OnFetchPrepare()
        {
        }

        protected virtual void OnFetchFinish()
        {
        }

    }

}
